<template>
  <div class="app-container">
    <!-- 使用封装的加载遮罩组件 -->
    <loading-overlay :visible="uploadLoading" text="正在处理数据，请稍候..." />
    <!-- 过滤栏 -->
    <filter-container 
      ref="filterContainer"
      :total="total" 
      search-placeholder="请输入FS号"
      @search="handleFilter"
    >
      <template #filter-items>
        <!-- 改码状态选择器 -->
        <el-select
          v-model="listQuery.is_changecode"
          placeholder="改码状态"
          clearable
          class="filter-item delete-select"
          @change="handleFilter"
        >
          <el-option label="改码" :value="true" />
          <el-option label="非改码" :value="false" />
        </el-select>
        
        <!-- 自提状态选择器 -->
        <el-select
          v-model="listQuery.is_pickup"
          placeholder="自提状态"
          clearable
          class="filter-item delete-select"
          @change="handleFilter"
        >
          <el-option label="自提" :value="true" />
          <el-option label="非自提" :value="false" />
        </el-select>
      </template>
      <template #action-buttons>
        <el-button
          v-if="multipleSelection.length > 0"
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-button
          v-if="multipleSelection.length > 0"
          class="filter-item"
          type="warning"
          icon="el-icon-date"
          @click="handleBatchUpdateDate"
        >
          批量修改日期
        </el-button>
        <el-upload
          ref="upload"
          class="filter-item upload-button"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
        >
          <el-button class="filter-item" type="success" icon="el-icon-plus" style="height: 40px;">
            新增本地单
          </el-button>
        </el-upload>
        <el-button
          v-if="multipleSelection.length > 0"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="handleExport"
        >
          导出Excel
        </el-button>
      </template>
      <template #selection-info>
        <span v-if="multipleSelection.length > 0" class="selection-info">
          已选择 <span class="selection-count">{{ multipleSelection.length }}</span> 条数据
        </span>
      </template>
    </filter-container>
    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
      class="custom-table"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column label="订单号" prop="fs_no" align="center" min-width="160">
        <template slot-scope="{row}">
          <div class="order-no-container">
            <el-tooltip v-if="row.remark" effect="dark" placement="top">
              <div slot="content">
                <p style="margin: 0; white-space: pre-wrap;">{{ row.remark }}</p>
              </div>
              <i class="el-icon-warning remark-icon"></i>
            </el-tooltip>
            <span class="copy-text" @click="handleCopy(row.fs_no)">{{ row.fs_no }}</span>
          </div>
          <div class="tags-container">
            <div v-if="row.is_changecode">
              <el-badge :value="row.changecode_id_count || 0" :max="99" class="change-code-badge">
                <el-tag size="mini" class="change-code-tag" style="color: #F56C6C;">改码</el-tag>
              </el-badge>
            </div>
            <el-tooltip v-if="row.is_pickup" effect="dark" placement="top">
              <div slot="content">
                <p style="margin: 0;">自提时间：{{ row.pickup_time ? row.pickup_time.replace('T', ' ').replace('+09:00', '') : '无自提时间' }}</p>
              </div>
              <el-tag size="mini" class="pickup-tag" style="color: #67C23A;">自提</el-tag>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="物流员" prop="created_by_username" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.created_by_username || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货方式" align="center" min-width="90">
        <template slot-scope="{row}">
          <span :class="['shipping-method', row.shipping_method === 'YAMATO' ? 'yamato' : row.shipping_method === 'SAGAWA' ? 'sagawa' : '']">
            {{ row.shipping_method === 'YAMATO' ? '黑猫' : row.shipping_method === 'SAGAWA' ? '佐川' : row.shipping_method || '-' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="佐川金额" align="center" min-width="90">
        <template slot-scope="{row}">
          <span>{{ row.sagawa_price || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="黑猫金额" align="center" min-width="90">
        <template slot-scope="{row}">
          <span>{{ row.yamato_price || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="都道府県" align="center" min-width="120">
        <template slot-scope="{row}">
          <span class="copy-text" @click="handleCopy(postalCodeResults[row.postal_code] ? postalCodeResults[row.postal_code].address : row.state || '-')">
            {{ postalCodeResults[row.postal_code] ? postalCodeResults[row.postal_code].address : row.state || '-' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="邮编" prop="postal_code" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.postal_code }}</span>
          <el-tooltip v-if="postalCodeResults[row.postal_code]" effect="dark" placement="top">
            <div slot="content">
              <p>地址: {{ postalCodeResults[row.postal_code].address }}</p>
              <p>城市: {{ postalCodeResults[row.postal_code].city }}</p>
              <p>省份: {{ postalCodeResults[row.postal_code].prefecture }}</p>
            </div>
            <i class="el-icon-info" style="margin-left: 5px; color: #409EFF; cursor: pointer;"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="删除状态" prop="is_delete" align="center" min-width="90">
        <template slot-scope="{row}">
          <el-tag :type="row.is_delete ? 'danger' : 'success'">
            {{ row.is_delete ? '已删除' : '未删除' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_time" align="center" min-width="160">
        <template slot-scope="{row}">
          <span>{{ row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center" min-width="150">
        <template slot-scope="{row}">
          <span>{{ row.remark || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="箱数" prop="box_count" align="center" min-width="80">
        <template slot-scope="{row}">
          <span>{{ row.box_count || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="体积" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ calculateVolume(row) || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="140" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <div class="action-buttons">
            <el-button type="primary" size="mini" @click="temp = Object.assign({}, row); dialogFormVisible = true; $nextTick(() => $refs['dataForm'].clearValidate())">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      :page-sizes="[100, 500, 1000, 1500, 2000]"
      @pagination="handlePaginationChange"
    />
    <!-- 编辑本地单 -->
    <el-dialog title="编辑本地单" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
      >
        <el-divider content-position="left">改码信息</el-divider>
        <el-form-item label="改码状态" prop="is_changecode">
          <el-switch
            v-model="temp.is_changecode"
            active-text="改码"
            inactive-text="非改码"
            active-color="#F56C6C"
          />
        </el-form-item>
        <el-form-item label="改码数量" prop="changecode_id_count">
          <el-input
            v-model="temp.changecode_id_count"
            placeholder="请输入改码数量"
            :disabled="!temp.is_changecode"
          />
        </el-form-item>

        <el-divider content-position="left">自提信息</el-divider>
        <el-form-item label="是否自提" prop="is_pickup">
          <el-switch
            v-model="temp.is_pickup"
            active-text="自提"
            inactive-text="非自提"
            active-color="#67C23A"
            @change="handlePickupChange"
          />
        </el-form-item>
        <el-form-item label="自提时间" prop="pickup_time">
          <el-date-picker
            v-model="temp.pickup_time"
            type="datetime"
            placeholder="选择自提时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
            :disabled="!temp.is_pickup"
          />
        </el-form-item>

        <el-divider content-position="left">发货信息</el-divider>
        <div class="volume-info" style="margin-bottom: 20px;">
          <span>体积：{{ calculateVolume(temp) || '-' }} cm³</span>
        </div>
        <el-form-item label="发货方式" prop="shipping_method">
          <el-select v-model="temp.shipping_method" placeholder="请选择">
            <el-option label="佐川" value="SAGAWA" />
            <el-option label="黑猫" value="YAMATO" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流号" prop="tracking_number">
          <el-input v-model="temp.tracking_number" placeholder="请输入物流号" />
        </el-form-item>
        <el-form-item label="都道府県" prop="state">
          <el-input v-model="temp.state" />
        </el-form-item>
        <el-form-item label="邮编" prop="postal_code">
          <el-input v-model="temp.postal_code" />
        </el-form-item>
        <el-form-item label="地址1">
          <el-input :value="temp.address1" readonly disabled />
        </el-form-item>
        <el-form-item label="地址2">
          <el-input :value="temp.address2" readonly disabled />
        </el-form-item>
        <el-form-item label="城市">
          <el-input :value="temp.city" readonly disabled />
        </el-form-item>
        <el-form-item label="电话">
          <el-input :value="temp.phone_number" readonly disabled />
        </el-form-item>
        <el-form-item label="收货人">
          <el-input :value="temp.attention" readonly disabled />
        </el-form-item>
        <el-form-item label="公司">
          <el-input :value="temp.company_name" readonly disabled />
        </el-form-item>
        <el-divider content-position="left">其他信息</el-divider>
        <el-form-item label="创建日期" prop="create_time">
          <el-date-picker
            v-model="temp.create_time"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="箱数" prop="box_count">
          <el-input v-model="temp.box_count" placeholder="请输入箱数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="备注完成状态">
          <el-switch
            v-model="temp.remark_status"
            :active-value="true"
            :inactive-value="false"
            active-text="备注完成"
            inactive-text="未完成"
            active-color="#67C23A"
            inactive-color="#E6A23C"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <!-- 批量修改日期对话框 -->
    <el-dialog title="批量修改创建日期" :visible.sync="batchDateDialogVisible" width="600px">
      <el-form ref="batchDateForm" :model="batchDateForm" :rules="batchDateRules" label-width="120px">
        <el-form-item label="选择日期时间" prop="createTime">
          <el-date-picker
            v-model="batchDateForm.createTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item>
          <p style="color: #909399; font-size: 14px; margin: 0;">
            将批量修改 <strong style="color: #F56C6C;">{{ multipleSelection.length }}</strong> 条记录的创建日期
          </p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchDateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchUpdateDate" :loading="batchDateLoading">确认修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchLocalList, updateLocalOrder, deleteLocalOrder, searchPostalCode, getShippingMethod, batchDeleteLocalOrders, exportLocalOrder, batchUpdateLocalOrdersDate } from '@/api/shipping'
import Pagination from '@/components/Pagination'
import FilterContainer from './components/FilterContainer.vue'
import LoadingOverlay from './components/LoadingOverlay.vue'

export default {
  name: 'LocalOrder',
  components: { 
    Pagination,
    FilterContainer,
    LoadingOverlay
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      postalCodeResults: {},
      listQuery: {
        page: 1,
        page_size: 100,
        keyword: '',
        is_delete: false,
        is_changecode: undefined,  // 改码状态过滤
        is_pickup: undefined,      // 自提状态过滤
      },
      uploadUrl: process.env.VUE_APP_BASE_API.replace(/['"]/g, '') + '/v1/shipping/local/import',
      uploadHeaders: {
        Authorization: 'Bearer ' + this.$store.getters.token
      },
      statusOptions: [
        { label: '已删除', value: true },
        { label: '未删除', value: false }
      ],
      temp: {
        id: undefined,
        fs_no: '',
        shipping_method: '',
        state: '',
        postal_code: '',
        is_delete: false,
        remark: '',
        tracking_number: '',
        is_changecode: false,
        changecode_id_count: '',
        is_pickup: false,
        pickup_time: '',
        box_count: '',
        address1: '',
        address2: '',
        city: '',
        phone_number: '',
        attention: '',
        company_name: '',
        remark_status: false
      },
      dialogFormVisible: false,
      rules: {
        state: [{ required: true, message: '都道府県必填', trigger: 'blur' }],
        postal_code: [{ required: true, message: '邮编必填', trigger: 'blur' }],
        pickup_time: [
          {
            validator: (rule, value, callback) => {
              if (this.temp.is_pickup && !value) {
                callback(new Error('自提时间不能为空'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      multipleSelection: [],
      isTrackingRequestLocked: false,
      lastTrackingRequestTime: 0,
      trackingRequestTimeout: 5000,
      uploadLoading: false,
      batchDateDialogVisible: false,
      batchDateLoading: false,
      batchDateForm: {
        createTime: ''
      },
      batchDateRules: {
        createTime: [{ required: true, message: '请选择创建日期', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handlePickupChange(value) {
      // 当自提状态改变时，清空自提时间并重新验证
      if (!value) {
        this.temp.pickup_time = ''
      }
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.dataForm.validateField('pickup_time')
      })
    },
    handleFilter(params) {
      this.listQuery.page = 1
      
      // 处理日期范围
      if (params.dateRange && params.dateRange.length === 2) {
        this.listQuery.start_date = params.dateRange[0]
        this.listQuery.end_date = params.dateRange[1]
      } else {
        delete this.listQuery.start_date
        delete this.listQuery.end_date
      }
      
      // 更新查询参数
      this.listQuery = {
        ...this.listQuery,
        keyword: params.keyword,
        is_delete: params.is_delete
      }

      // 如果is_delete为null或undefined，则删除该参数，显示所有数据
      if (params.is_delete === null || params.is_delete === undefined) {
        delete this.listQuery.is_delete
      }

      this.getList()
    },
    async getList() {
      this.listLoading = true
      try {
        const response = await fetchLocalList(this.listQuery)
        
        let items = []
        let total = 0
        
        if (response.results && response.results.data && response.results.data.items) {
          items = response.results.data.items
          total = response.count || 0
        }
        
        this.list = items
        this.total = total
        this.listLoading = false

        // 等待邮编信息查询完成
        await this.queryPostalCodes()
      } catch (error) {
        console.error('获取数据失败:', error)
        this.list = []
        this.total = 0
        this.listLoading = false
      }
    },
    isEmptyShippingMethod(method) {
      return !method || method === '' || method === null || method === undefined
    },
    async queryPostalCodes() {
      if (!this.list) return
      const searchData = this.list
        .filter(item => this.isEmptyShippingMethod(item.shipping_method) && item.postal_code && item.fs_no)
        .map(item => ({
          postal_code: item.postal_code,
          fs_no: item.fs_no
        }))

      if (searchData.length > 0) {
        try {
          const response = await searchPostalCode(searchData)
          if (response.code === 200 && response.data && response.data.results) {
            response.data.results.forEach(result => {
              // 适配新的邮编查询工具，result.address 现在包含完整的地址信息（如：東京都目黒区東山）
              if (result.address) {
                this.$set(this.postalCodeResults, result.postal_code, {
                  address: result.address,
                  city: result.city || '',
                  prefecture: result.prefecture || ''
                })
                const index = this.list.findIndex(item => item.fs_no === result.fs_no)
                if (index !== -1) {
                  // 将查询到的地址信息赋值给 order.state
                  this.$set(this.list[index], 'state', result.address)
                }
              }
            })
            // 等待发货方式查询完成
            await this.queryShippingMethod()
          }
        } catch (error) {
          console.error('查询邮编信息失败:', error)
        }
      }
    },
    async queryShippingMethod() {
      if (!this.list) return

      const itemsNeedShippingMethod = this.list
        .filter(item => this.isEmptyShippingMethod(item.shipping_method) && item.fs_no)

      if (itemsNeedShippingMethod.length > 0) {
        const fsNos = itemsNeedShippingMethod.map(item => item.fs_no)
        try {
          const response = await getShippingMethod({
            fs_no: fsNos
          })
          if (response.code === 200 && response.data && response.data.results) {
            response.data.results.forEach(result => {
              const index = this.list.findIndex(item => item.fs_no === result.fs_no)
              if (index !== -1 && result.shipping_method) {
                this.$set(this.list[index], 'shipping_method', result.shipping_method)
                this.$set(this.list[index], 'sagawa_price', result.sagawa_price)
                this.$set(this.list[index], 'yamato_price', result.yamato_price)
              }
            })
          }
        } catch (error) {
          console.error('批量获取发货方式失败:', error)
        }
      }
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                     file.type === 'application/vnd.ms-excel'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('文件大小不能超过 2MB!')
        return false
      }
      return true
    },
    async handleUploadSuccess(response) {
      // 显示加载遮罩
      this.uploadLoading = true
      
      // 检查响应是否成功
      if (response.code === 200 && response.data) {
        const { success_count, error_count, skipped_count, error_records } = response.data
        
        // 构建基础成功消息
        let message = ''
        let type = 'success'
        
        if (success_count > 0) {
          message = `成功导入 ${success_count} 条记录`
          
          // 添加其他统计信息
          if (skipped_count > 0) {
            message += `，跳过 ${skipped_count} 条不合法数据`
          }
          if (error_count > 0) {
            message += `，${error_count} 条记录导入失败`
          }
        } else {
          message = `导入失败：没有成功导入的记录`
          type = 'warning'
          
          if (skipped_count > 0) {
            message += `，跳过 ${skipped_count} 条不合法数据`
          }
        }
        
        // 如果有错误记录，显示详细错误信息
        if (error_count > 0 && error_records && error_records.length > 0) {
          // 统计错误类型
          const errorStats = {}
          error_records.forEach(record => {
            const errorType = record.error
            if (!errorStats[errorType]) {
              errorStats[errorType] = []
            }
            errorStats[errorType].push(record.fs_no)
          })
          
          // 构建详细错误消息
          let detailMessage = message + '\n\n详细失败信息：\n'
          Object.keys(errorStats).forEach(errorType => {
            const fsNumbers = errorStats[errorType]
            detailMessage += `\n• ${errorType}：${fsNumbers.length}条`
            
            // 如果同类型错误较少，显示具体的FS编号
            if (fsNumbers.length <= 10) {
              detailMessage += `\n  ${fsNumbers.join(', ')}`
            } else {
              // 如果错误较多，只显示前几个
              detailMessage += `\n  ${fsNumbers.slice(0, 10).join(', ')} 等${fsNumbers.length}条`
            }
          })
          
          // 使用MessageBox显示详细信息
          this.$alert(detailMessage, '导入结果详情', {
            confirmButtonText: '确定',
            type: type,
            customClass: 'upload-result-dialog'
          })
        } else {
          // 没有错误记录，使用简单通知
          this.$notify({
            title: '导入完成',
            message: message,
            type: type,
            duration: 4000
          })
        }

        // 如果有成功导入的记录，等待数据处理完成后刷新页面
        if (success_count > 0) {
          try {
            await this.getList()
            // 等待一下确保所有异步操作完成
            setTimeout(() => {
              this.uploadLoading = false // 隐藏加载遮罩
              location.reload()
            }, 1000)
          } catch (error) {
            console.error('获取数据失败:', error)
            // 即使失败也刷新页面
            setTimeout(() => {
              this.uploadLoading = false // 隐藏加载遮罩
              location.reload()
            }, 1000)
          }
        } else {
          // 没有成功记录，直接隐藏加载遮罩
          this.uploadLoading = false
        }
      } else {
        // 隐藏加载遮罩
        this.uploadLoading = false
        this.$notify({
          title: '导入失败',
          message: response.message || '导入失败，请重试',
          type: 'error',
          duration: 3000
        })
      }
    },
    handleUploadError(err) {
      // 隐藏加载遮罩
      this.uploadLoading = false
      console.error('Upload error:', err)
      this.$notify({
        title: '导入失败',
        message: '导入失败',
        type: 'error',
        duration: 3000
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        fs_no: '',
        shipping_method: '',
        state: '',
        postal_code: '',
        is_delete: false,
        remark: '',
        tracking_number: '',
        is_changecode: false,
        changecode_id_count: '',
        is_pickup: false,
        pickup_time: '',
        box_count: '',
        address1: '',
        address2: '',
        city: '',
        phone_number: '',
        attention: '',
        company_name: '',
        remark_status: false
      }
    },
    async updateData() {
      try {
        const valid = await this.$refs['dataForm'].validate()
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          await updateLocalOrder(tempData)
          const index = this.list.findIndex(v => v.id === this.temp.id)
          this.temp.shipping_method_class = this.temp.shipping_method === 'YAMATO' ? 'yamato' : this.temp.shipping_method === 'SAGAWA' ? 'sagawa' : ''
          this.list.splice(index, 1, this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('更新失败:', error)
        
        // 解析错误信息
        let errorMessage = '更新失败'
        if (error.response && error.response.data) {
          const errorData = error.response.data
          if (errorData.error) {
            // 如果有具体的字段错误，显示第一个字段的错误信息
            const firstError = Object.values(errorData.error)[0]
            if (Array.isArray(firstError) && firstError.length > 0) {
              errorMessage = firstError[0]
            } else if (typeof firstError === 'string') {
              errorMessage = firstError
            }
          } else if (errorData.message) {
            errorMessage = errorData.message
          }
        }
        
        this.$notify({
          title: '错误',
          message: errorMessage,
          type: 'error',
          duration: 3000
        })
      }
    },
    async handleModifyStatus(row) {
      const text = row.is_delete ? '恢复' : '删除'
      try {
        await this.$confirm(`确认要${text}该订单吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const is_delete = !row.is_delete
        await updateLocalOrder({ id: row.id, is_delete })
        const index = this.list.findIndex(v => v.id === row.id)
        this.list.splice(index, 1, { ...row, is_delete })
        this.$notify({
          title: '成功',
          message: `${text}成功`,
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        if (error !== 'cancel') {
          console.error('操作失败:', error)
          this.$notify({
            title: '错误',
            message: '操作失败',
            type: 'error',
            duration: 2000
          })
        }
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('警告：删除后数据将永久丢失，无法恢复！', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        
        await deleteLocalOrder(row.id)
        const index = this.list.findIndex(v => v.id === row.id)
        this.list.splice(index, 1)
        this.total = this.total - 1
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$notify({
            title: '错误',
            message: '删除失败',
            type: 'error',
            duration: 2000
          })
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleCopy(text) {
      const textarea = document.createElement('textarea')
      textarea.value = text
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      this.$notify({
        title: '成功',
        message: '复制成功',
        type: 'success',
        duration: 2000
      })
    },
    async handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的订单')
        return
      }
      
      try {
        await this.$confirm(`删除后该记录将不再显示在列表中。`, '批量删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const fsNos = this.multipleSelection.map(item => item.fs_no)
        await batchDeleteLocalOrders(fsNos)
        this.$notify({
          title: '成功',
          message: '批量删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          this.$notify({
            title: '错误',
            message: '批量删除失败',
            type: 'error',
            duration: 2000
          })
        }
      }
    },
    handlePaginationChange({ page, limit }) {
      this.listQuery.page = page
      this.listQuery.page_size = limit
      this.getList()
    },
    async handleExport() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要导出的数据')
        return
      }
      
      try {
        const ids = this.multipleSelection.map(item => item.id)
        const response = await exportLocalOrder({ ids })
        const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = `本地订单导出_${new Date().getTime()}.xlsx`
        link.click()
        window.URL.revokeObjectURL(link.href)
        this.$notify({
          title: '成功',
          message: '导出成功',
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        console.error('导出失败:', error)
        this.$notify({
          title: '错误',
          message: error.message || '导出失败',
          type: 'error',
          duration: 2000
        })
      }
    },
    getShippingMethodClass(method) {
      const baseClass = 'shipping-method'
      if (method === 'YAMATO') {
        return [baseClass, 'yamato']
      } else if (method === 'SAGAWA') {
        return [baseClass, 'sagawa']
      }
      return [baseClass]
    },
    getShippingMethodText(method) {
      if (method === 'YAMATO') return '黑猫'
      if (method === 'SAGAWA') return '佐川'
      return method || '-'
    },
    calculateVolume(row) {
      if (row.length && row.width && row.height) {
        const volume = parseFloat(row.length) + parseFloat(row.width) + parseFloat(row.height)
        return volume.toFixed(1)
      }
      return null
    },
    handleBatchUpdateDate() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要修改日期的订单')
        return
      }
      
      // 重置表单
      this.batchDateForm.createTime = ''
      this.batchDateDialogVisible = true
      this.$nextTick(() => {
        this.$refs.batchDateForm.clearValidate()
      })
    },
    async confirmBatchUpdateDate() {
      try {
        const valid = await this.$refs.batchDateForm.validate()
        if (!valid) {
          return
        }
        
        this.batchDateLoading = true
        const fsNos = this.multipleSelection.map(item => item.fs_no)
        await batchUpdateLocalOrdersDate(fsNos, this.batchDateForm.createTime)
        
        this.$notify({
          title: '成功',
          message: `成功修改 ${fsNos.length} 条记录的创建日期`,
          type: 'success',
          duration: 3000
        })
        
        this.batchDateDialogVisible = false
        this.getList() // 刷新列表
      } catch (error) {
        console.error('批量修改日期失败:', error)
        this.$notify({
          title: '错误',
          message: error.message || '批量修改日期失败',
          type: 'error',
          duration: 3000
        })
      } finally {
        this.batchDateLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/dialog-common.scss';
@import '@/styles/shipping-common.scss';

/* 体积信息样式 */
.volume-info {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin: 10px 0;
  font-size: 14px;
  color: #606266;
}

/* 改码徽标样式 */
.change-code-badge {
  margin-top: 5px;
  ::v-deep .el-badge__content {
    background-color: #F56C6C;
    border-color: #F56C6C;
    font-size: 10px;
    height: 16px;
    line-height: 16px;
    padding: 0 5px;
    min-width: 16px;
  }
}

/* 状态过滤器组合样式 */
.status-filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 4px;
  height: 40px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #c0c4cc;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }
  
  .status-select {
    height: 32px !important;
    margin: 0;
    
    ::v-deep .el-input__inner {
      height: 32px !important;
      line-height: 32px !important;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      background: #fff;
      font-size: 13px;
      transition: all 0.3s ease;
      
      &:focus {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
      }
      
      &:hover {
        border-color: #c0c4cc;
      }
    }
    
    ::v-deep .el-input__suffix {
      height: 32px;
      display: flex;
      align-items: center;
    }
  }
  
  /* 第一个选择器样式 */
  .status-select:first-child {
    width: 110px;
    
    ::v-deep .el-input__inner {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
      border-right: none;
    }
  }
  
  /* 第二个选择器样式 */
  .status-select:last-child {
    width: 110px;
    
    ::v-deep .el-input__inner {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .status-filter-group {
    flex-direction: column;
    height: auto;
    padding: 6px;
    gap: 4px;
    
    .status-select:first-child ::v-deep .el-input__inner {
      border-radius: 6px 6px 0 0;
      border-right: 1px solid #dcdfe6;
      border-bottom: none;
    }
    
    .status-select:last-child ::v-deep .el-input__inner {
      border-radius: 0 0 6px 6px;
    }
  }
}

/* 上传结果对话框样式 */
::v-deep .upload-result-dialog {
  .el-message-box__message {
    white-space: pre-line;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 13px;
    line-height: 1.6;
    max-height: 400px;
    overflow-y: auto;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
    color: #495057;
  }
  
  .el-message-box__title {
    font-weight: 600;
    color: #343a40;
  }
  
  .el-message-box__content {
    padding-bottom: 20px;
  }
}
</style>
